﻿using System;
using System.Data;
using System.Collections.Generic;

using System.Text;
using TimKen.DataEntity;
using TimKen.DataAccess;

namespace TimKen.BussLogic
{
    /// <summary>
    /// 产品业务逻辑操作类
    /// </summary>
    public class ProductManager
    {
        private readonly TimKen.DataAccess.ProductDAO dal = new TimKen.DataAccess.ProductDAO();
        private readonly TimKen.BussLogic.SpecialPriceManager spm = new SpecialPriceManager();
        private readonly TimKen.BussLogic.CustomerDiscountManager cdm = new CustomerDiscountManager();
        private readonly TimKen.BussLogic.PDiffPriceManager pdpm = new PDiffPriceManager();
        public ProductManager()
        { }
        #region  成员方法
        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(int ProductID)
        {
            return dal.Exists(ProductID);
        }

        /// <summary>
        /// 增加一条数据
        /// </summary>
        public int Add(TimKen.DataEntity.Product model)
        {
            return dal.Add(model);
        }

        /// <summary>
        /// 更新一条数据
        /// </summary>
        public void Update(TimKen.DataEntity.Product model)
        {
            dal.Update(model);
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public void Delete(int ProductID)
        {

            dal.Delete(ProductID);
        }

        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public TimKen.DataEntity.Product GetModel(int ProductID)
        {

            return dal.GetModel(ProductID);
        }
        public TimKen.DataEntity.Product GetModel(string itemCode)
        {

            return dal.GetModel(itemCode);
        }


        /// <summary>
        /// 根据产品id获取产品所有属性 中英文
        /// </summary>
        /// <param name="productID"></param>
        /// <param name="languageID"></param>
        /// <returns></returns>
        public DataSet GetAttributeWithValueByProductID(string productID)
        {
            return dal.GetAttributeWithValueByProduct(productID);
        }

        public DataSet GetPDiffPriceByProductCode(string itemCode)
        {
            return dal.GetPDiffPriceByProductCode(itemCode);
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet GetList(string strWhere)
        {
            return dal.GetList(strWhere);
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet GetAllList()
        {
            return GetList("");
        }


        public void SetPromote(int ProductID, bool IsPromote, decimal? PromoteDiscount, DateTime? PromoteFrom, DateTime? PromoteTo)
        {
            if (!IsPromote)
                dal.UpdatePromote(ProductID, false, null, null, null);
            else
                dal.UpdatePromote(ProductID, IsPromote, PromoteDiscount, PromoteFrom, PromoteTo);
        }


        /// <summary>
        /// 获取促销列表
        /// </summary>
        public DataSet GetPromoteList(int PageSize, int PageIndex, int LanguageID, int BrandID, int CategoryID, string KeyWords, string IsPromote, bool IsDisplay)
        {
            string promoteWhere = "";

            if (IsPromote == "-1")
                promoteWhere = " And [IsPromote]>" + IsPromote;
            else if (IsPromote == "0")
                promoteWhere = " And [IsPromote]=" + IsPromote;
            else
                promoteWhere = " And [IsPromote]=" + IsPromote ;
            // + " AND [PromoteFrom] <='" + DateTime.Now.ToString() + "' AND [PromoteTo] >='" +DateTime.Now.ToString()  + "'"


            return dal.GetList(PageSize, PageIndex, LanguageID, BrandID, CategoryID, KeyWords, promoteWhere, false, IsDisplay, 0);
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet GetList(int PageSize, int PageIndex, int LanguageID, int BrandID, int CategoryID, string KeyWords, string ProductIDWhere,bool ShowFreeze,bool  IsDisplay,int industryId)
        {
            return dal.GetList(PageSize, PageIndex, LanguageID, BrandID, CategoryID, KeyWords, ProductIDWhere, ShowFreeze, IsDisplay, industryId);
        }





        public DataSet GetList(int PageSize, int PageIndex, int LanguageID, int BrandID, int CategoryID, string KeyWords, string ProductIDWhere, string ProductDescript, bool ShowFreeze, bool IsDisplay,int IndustryID) 
        {
            return dal.GetList(PageSize, PageIndex, LanguageID, BrandID, CategoryID, KeyWords, ProductIDWhere,ProductDescript,ShowFreeze,IsDisplay,IndustryID);
        }


        public void UploadImg(int ProductID, string impName)
        {
            dal.UploadImg(ProductID, impName);
        }



        public decimal GetProductPriceByCustomer(Product p, int customerID, decimal Quantity)
        {

            if (p == null)
            {
                throw new NoNullAllowedException("Product");
            }


            PPrice  Price  = GetProductBasePrice(p.ProductID, customerID);

            decimal BasePrice = Price.Price;

            if (BasePrice == null || BasePrice == 0)
                return 0;

            decimal NetPrice = BasePrice;//最终计算结果



            int productID = p.ProductID;

            /*如果存在促销价在促销期内使用促销价 1 */
            if (p.IsPromote && p.PromoteFrom <= DateTime.Now && DateTime.Now <= p.PromoteTo)
            {
                if (!p.PromoteDiscount.HasValue)
                {
                    throw new NoNullAllowedException("Product.PromoteDiscount");
                }
                else
                {
                    NetPrice = BasePrice * p.PromoteDiscount.Value;
                }
                return NetPrice;
            }

            //直接返回特殊价格的数
            SpecialPrice sp = spm.GetModel(customerID, productID);

            //直接返回特殊价格的数
            if (spm.Exists(customerID, productID))/*特殊价格 2 */
            {
                if ((SpecialPriceType)sp.SpecialType == SpecialPriceType.SpecialPrice)
                {
                    return sp.Price.Value;
                }
            }

            /*正常折扣价格 3 */
            DataSet ds = cdm.GetList(" CustomerID=" + customerID + " and (StrategyID=" + p.ProductLineID + " or StrategyID=" + p.DiscountGroupID + ")");
            if (ds.Tables[0].Rows.Count == 1)
            {
                NetPrice = BasePrice * Convert.ToDecimal(ds.Tables[0].Rows[0]["Discount"]);//获取该客户所采用的折扣方式   产品线 还是 产品分组
            }
            else if (ds.Tables[0].Rows.Count > 1)
            {
                throw new InvalidOperationException("价格策略只能有一条 产品线 或者 产品类型策略");
            }
            //分量计价------------------------
            IList<PDiffPrice> list = pdpm.GetList(" ItemCode='" + p.ItemCode + "' order by Qty DESC");

            if (list.Count > 0)
            {
                decimal discount = 1.0M;
                foreach (PDiffPrice pdp in list)
                {
                    if (pdp.Qty <= Quantity)
                    {
                        discount = pdp.Discount;
                        break;
                    }
                }
                NetPrice = NetPrice * discount;
            }

            //定义了特殊折扣-----------------------------
            if (sp != null && (SpecialPriceType)sp.SpecialType == SpecialPriceType.Discount)
            {   //特殊折扣的折扣
                NetPrice = NetPrice * sp.SpecialDiscount.Value;
            }
            return NetPrice;
            //以上折扣为乘积关系  
        }

        /// <summary>
        /// 返回某客户的产品价格
        /// </summary>
        /// <param name="productID"></param>
        /// <param name="customerID"></param>
        /// <returns></returns>
        public decimal GetProductPriceByCustomer(int productID, int customerID, decimal Quantity)
        {
            Product p = this.GetModel(productID);
            return GetProductPriceByCustomer(p, customerID, Quantity);
        }




        public long GetProductCountByCategoryID(int categoryID, bool IsDisplay)
        {
            DataSet ds = dal.GetList(10, 1, 1, 0, categoryID, "", "", false, IsDisplay,0);

            return long.Parse(ds.Tables[1].Rows[0][0].ToString());
        }

        public long GetProductCountByCategoryID(int categoryID)
        {
            DataSet ds = dal.GetList(10, 1, 1, 0, categoryID, "", "", false, false,0);

            return long.Parse(ds.Tables[1].Rows[0][0].ToString());
        }


        /// <summary>
        /// 获取此产品的分类图片,如果此分类没有图片,则获取上级分类的图片,类推
        /// </summary>
        /// <param name="productID"></param>
        /// <returns></returns>
        public string GetProductImage(int productID) 
        {
            Product p = this.GetModel(productID);
            PCategoryManager pcm = new PCategoryManager();




            //修改 by miaozy  添加产品的图片上传功能
            if (!string.IsNullOrEmpty(p.Image))
                return p.Image;

    


            return pcm.GetCategoryImage(p.CategoryID.Value);
        }


        public PPrice GetProductBasePrice(int productID,int customerID)
        {
            Product product = GetModel(productID);
            CustomerManager cm = new CustomerManager();
            Customer customer = cm.GetModel(customerID);

            //未登录、已用户看到价格表16的单价，币种为RMB
            if(customer == null)
                return GetProductBasePrice(product.ItemCode.Trim(), "RMB", 16);

            bool isAuthorization = GetProductAuthorization(productID, customerID);

            if (isAuthorization)
                return GetProductBasePrice(product.ItemCode.Trim(), customer.Currency, 15);
            else
                //登录未授权的用户看到的是16的单价，币种为客户的币种
                return GetProductBasePrice(product.ItemCode.Trim(), customer.Currency, 16);

        }


        public bool GetProductAuthorization(int productID, int customerID)
        {
            Product product = GetModel(productID);
            if (product != null)
            {
                CustomerDiscountManager cdm = new CustomerDiscountManager();
                /*正常折扣价格 3 */
                DataSet ds = cdm.GetList(" CustomerID=" + customerID + " and (StrategyID=" + product.ProductLineID + " or StrategyID=" + product.DiscountGroupID + ")");
                if (ds.Tables[0].Rows.Count == 1)
                {
                    return true;
                }
            }
            return false;
        }


        public PPrice GetProductBasePrice(string ItemCode, string Currency, int PriceList)
        {
            PPrice price = new PPrice();

            string sql = "SELECT Price  FROM PPrice  WHERE ItemCode='{0}' AND Currency='{1}' AND PriceList={2} ";
            sql = string.Format(sql, ItemCode.Trim(), Currency.Trim(),PriceList);
            object  result= DbHelperSQL.GetSingle(sql);

            if (result == null)
            {
                price.Currency = "RMB";
                price.Price = 0;
                price.ItemCode = ItemCode;
                return price;
            }
 

            price.Currency =  Currency;
            price.Price =  decimal.Round(decimal.Parse(result.ToString()),2);
            price.ItemCode = ItemCode;
            price.PriceList = PriceList;
            return price;

        }

        #endregion  成员方法
    }
}

